package com.device.service;

import com.device.dto.ModbusConfigDTO;
import com.device.entity.DeviceKey;
import com.device.repository.DeviceKeyRepository;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;

/**
 * Key表单服务
 */
@Service
public class DeviceKeyService {
    
    @Autowired
    private DeviceKeyRepository deviceKeyRepository;
    
    /**
     * 根据分设备ID获取Key表单列表
     */
    public List<DeviceKey> getKeysBySubDeviceId(UUID subDeviceId) {
        return deviceKeyRepository.findBySubDeviceIdOrderByKeyNumberAsc(subDeviceId);
    }
    
    /**
     * 根据分设备ID获取Modbus配置DTO列表
     */
    public List<ModbusConfigDTO> getModbusConfigsBySubDeviceId(UUID subDeviceId) {
        List<DeviceKey> deviceKeys = deviceKeyRepository.findBySubDeviceIdOrderByKeyNumberAsc(subDeviceId);
        return deviceKeys.stream()
                .map(this::convertToModbusConfigDTO)
                .collect(Collectors.toList());
    }
    
    /**
     * 将DeviceKey实体转换为ModbusConfigDTO
     */
    private ModbusConfigDTO convertToModbusConfigDTO(DeviceKey deviceKey) {
        ModbusConfigDTO modbusConfigDTO = new ModbusConfigDTO();
        BeanUtils.copyProperties(deviceKey, modbusConfigDTO);
        return modbusConfigDTO;
    }
    
    /**
     * 根据ID获取Key表单
     */
    public DeviceKey getKeyById(UUID id) {
        return deviceKeyRepository.findById(id).orElse(null);
    }
    
    /**
     * 创建Key表单
     */
    @Transactional
    public DeviceKey createKey(DeviceKey deviceKey) {
        // 检查Key编号在同一分设备下是否已存在
        if (deviceKeyRepository.countBySubDeviceIdAndKeyNumber(
                deviceKey.getSubDeviceId(), deviceKey.getKeyNumber()) > 0) {
            throw new RuntimeException("该分设备下编号已存在");
        }
        
        // 确保ID不为空
        if (deviceKey.getId() == null) {
            deviceKey.setId(UUID.randomUUID());
        }
        deviceKey.setCreatedTime(System.currentTimeMillis());
        deviceKey.setUpdatedTime(System.currentTimeMillis());
        
        return deviceKeyRepository.save(deviceKey);
    }
    
    /**
     * 更新Key表单
     */
    @Transactional
    public DeviceKey updateKey(UUID id, DeviceKey deviceKey) {
        DeviceKey existingKey = deviceKeyRepository.findById(id).orElse(null);
        if (existingKey == null) {
            throw new RuntimeException("Key表单不存在");
        }
        
        // 检查Key编号在同一分设备下是否已存在（排除当前记录）
        if (deviceKeyRepository.countBySubDeviceIdAndKeyNumberAndIdNot(
                deviceKey.getSubDeviceId(), deviceKey.getKeyNumber(), id) > 0) {
            throw new RuntimeException("该分设备下编号已存在");
        }
        
        deviceKey.setId(id);
        deviceKey.setCreatedTime(existingKey.getCreatedTime());
        deviceKey.setUpdatedTime(System.currentTimeMillis());
        
        return deviceKeyRepository.save(deviceKey);
    }
    
    /**
     * 删除Key表单
     */
    @Transactional
    public void deleteKey(UUID id) {
        DeviceKey deviceKey = deviceKeyRepository.findById(id).orElse(null);
        if (deviceKey == null) {
            throw new RuntimeException("Key表单不存在");
        }
        
        deviceKeyRepository.deleteById(id);
    }
    
    /**
     * 批量删除Key表单
     */
    @Transactional
    public void deleteKeys(List<UUID> ids) {
        for (UUID id : ids) {
            deleteKey(id);
        }
    }
    
    /**
     * 根据分设备ID删除所有Key表单
     */
    @Transactional
    public void deleteKeysBySubDeviceId(UUID subDeviceId) {
        deviceKeyRepository.deleteBySubDeviceId(subDeviceId);
    }
    
    /**
     * 检查Key编号在同一分设备下是否存在
     */
    public boolean existsBySubDeviceIdAndKeyNumber(UUID subDeviceId, Integer keyNumber) {
        return deviceKeyRepository.countBySubDeviceIdAndKeyNumber(subDeviceId, keyNumber) > 0;
    }
    
    /**
     * 获取所有Key表单
     */
    public List<DeviceKey> getAllKeys() {
        return deviceKeyRepository.findAll();
    }
    
    /**
     * 根据分设备ID统计Key表单数量
     */
    public int countBySubDeviceId(UUID subDeviceId) {
        return Math.toIntExact(deviceKeyRepository.countBySubDeviceId(subDeviceId));
    }
}